Introduction
Welcome to Unit 15, where we transition from classification to regression problems.
Classification vs. Regression:
| Aspect | Classification | Regression |
|---|---|---|
| Output Type | Discrete labels | Continuous values |
| Examples | Spam detection, image classification | House price prediction, temperature forecasting |
| Loss Functions | Cross-entropy, Gini impurity | MSE, MAE, RMSE |
| Evaluation Metrics | Accuracy, Precision, Recall, F1, AUC-ROC | RMSE, MAE, R² |
This lecture covers:
- Introduction to regression problems
- Evaluation metrics for regression
- K-Nearest Neighbors (KNN) for regression
- Regression Trees (Decision Trees for regression)
- Comparison of regression algorithms
Real-world Regression Examples:
- Predicting house prices from size, location, and features
- Estimating rainfall from weather sensor data
- Forecasting stock prices or energy demand
- Predicting student GPA from study hours and attendance
- Estimating patient recovery time from medical measurements
Theory
From Classification to Regression
While classification and regression are different types of problems, they share a similar ML pipeline:
- Data collection
- Data preprocessing
- Handle missing values, outliers
- Feature scaling (critical for models using gradient descent)
- Encoding (relevant for mixed features)
- Train-test split (or train-val-test)
- Model training
- Choose algorithm (e.g., linear regression, regression trees, gradient boosting)
- Optimize using regression-specific loss (e.g., MSE, MAE)
- Evaluation
- Use regression metrics: RMSE, MAE, R²
- Not classification metrics: accuracy, F1-score, AUC-ROC
Evaluation: How Do We Measure Regression Performance?
Unlike classification, which uses metrics like accuracy and F1-score, regression requires different evaluation metrics:
Common Regression Metrics:
1. Mean Squared Error (MSE)
- Interpretation: Average squared difference between actual and predicted values
- Penalty: Penalizes large errors heavily (due to squaring)
- Units: (original units)² - can be hard to interpret
- Use case: When large errors are particularly undesirable
2. Root Mean Squared Error (RMSE)
- Interpretation: Square root of average squared error
- Advantage: Same units as the target variable → easier to interpret
- Penalty: Still penalizes large errors heavily
- Use case: Most common metric for regression, easy to interpret
3. Mean Absolute Error (MAE)
- Interpretation: Average absolute error
- Advantage: More robust to outliers than MSE/RMSE
- Units: Same as target variable
- Use case: When outliers are present and you want a robust metric
Choosing Between MSE, RMSE, and MAE:
| Metric | Sensitive to Outliers | Interpretable Units | Differentiable |
|---|---|---|---|
| MSE | ✅ Yes (heavily) | ❌ No (squared units) | ✅ Yes |
| RMSE | ✅ Yes (heavily) | ✅ Yes (original units) | ❌ No (due to square root) |
| MAE | ❌ No (robust) | ✅ Yes (original units) | ❌ No (due to absolute value) |
Regression Algorithms – Course Roadmap
This course will cover several regression algorithms:
- K-Nearest Neighbors (KNN) Regressor
- Non-parametric, instance-based
- Simple extension from KNN classification
- Regression Trees (Decision Trees)
- Non-parametric, rule-based
- Splits to minimize MSE
- Ordinary Least Squares (OLS) Regression
- Parametric, linear model
- Closed-form solution or gradient descent
- Polynomial Regression
- Extending OLS for non-linear relationships
- Feature engineering approach
- Regularized Regression (Ridge & Lasso)
- OLS with shrinkage/penalty
- Prevents overfitting, automatic feature selection
- Gradient Boosting for Regression
- Ensemble method (combines multiple trees)
- State-of-the-art performance
K-Nearest Neighbors (KNN) Regressor
Similar to K-NN classification, but instead of assigning a class label, K-NN regression predicts a continuous value by averaging the values of the k-nearest neighbors.
How KNN Regression Works:
- For a given query point, identify the k-nearest neighbors
- Compute the average (or weighted average) of their target values to get the prediction
- Typically uses Euclidean distance (or others, such as Manhattan) to find the nearest neighbors
- Often, closer neighbors are given higher weights in the averaging process to improve prediction accuracy
Characteristics:
- Computationally expensive: With large datasets, especially as the number of features grows
- Sensitive to choice of k: Small k can lead to noisy predictions, large k can oversmooth
- Sensitive to distance metric: Different distance metrics can give different results
- Works well for non-linear relationships: When the data distribution has local patterns rather than a global trend
- No training phase: KNN is a lazy learner - it memorizes the training data
KNN Regression Example
Consider a dataset with TV, Radio, and Newspaper advertising budgets, and Sales as the target:
| # | TV | Radio | Newspaper | Sales |
|---|---|---|---|---|
| R1 | 230.1 | 37.8 | 69.2 | ? |
| R2 | 44.5 | 39.3 | 45.1 | 10.4 |
| R3 | 17.2 | 45.9 | 69.3 | 9.3 |
| R4 | 151.5 | 41.3 | 58.5 | 18.5 |
| R5 | 180.8 | 10.8 | 58.4 | 12.9 |
| R6 | 8.7 | 48.9 | 75 | 7.2 |
Example predictions:
- When K = 1: Nearest neighbor is R4, hence predicted value = 18.5
- When K = 3: Nearest neighbors are R4, R5, and R6, hence predicted value = (18.5 + 12.9 + 7.2)/3 = 12.87
- When K = 5: Predicted value = 11.66
Regression Tree
The decision tree method can also be used for numerical response variables. Regression trees operate in much the same fashion as classification trees, but with key differences:
Regression Trees vs Classification Trees:
| Aspect | Classification Trees | Regression Trees |
|---|---|---|
| Target Variable | Categorical | Continuous |
| Leaf Node Value | Majority class (voting) | Average of training data in that leaf |
| Impurity Measure | Gini impurity, Entropy | Sum of squared deviations from the mean |
| Splitting Criterion | Maximize information gain | Minimize MSE (or variance) |
Key Insight: In regression trees, the value of the leaf node is determined by the average of the training data that were in that leaf. A typical impurity measure is the sum of the squared deviations from the mean of the leaf.
Important Notes:
- Data requirements: As with other data-driven methods, trees require large amounts of data
- Overfitting: Regression trees are prone to overfitting (we'll discuss this more later)
- Interpretability: One advantage of regression trees is that they are highly interpretable
Regression Tree Example
Consider a dataset for predicting the number of golf players based on weather conditions:
| Day | Outlook | Temp. | Humidity | Wind | Golf Players |
|---|---|---|---|---|---|
| 1 | Sunny | Hot | High | Weak | 25 |
| 2 | Sunny | Hot | High | Strong | 30 |
| 3 | Overcast | Hot | High | Weak | 46 |
| 4 | Rain | Mild | High | Weak | 45 |
| 5 | Rain | Cool | Normal | Weak | 52 |
| 6 | Rain | Cool | Normal | Strong | 23 |
| 7 | Overcast | Cool | Normal | Strong | 43 |
| 8 | Sunny | Mild | High | Weak | 35 |
| 9 | Sunny | Cool | Normal | Weak | 38 |
| 10 | Rain | Mild | Normal | Weak | 46 |
| 11 | Sunny | Mild | Normal | Strong | 48 |
| 12 | Overcast | Mild | High | Strong | 52 |
| 13 | Overcast | Hot | Normal | Weak | 44 |
| 14 | Rain | Mild | High | Strong | 30 |
Now consider the same dataset with Temperature as a numeric predictor:
| Day | Outlook | Temp. | Humidity | Wind | Golf Players |
|---|---|---|---|---|---|
| 1 | Sunny | 42 | High | Weak | 25 |
| 2 | Sunny | 38 | High | Strong | 30 |
| 3 | Overcast | 40 | High | Weak | 46 |
| 4 | Rain | 32 | High | Weak | 45 |
| 5 | Rain | 12 | Normal | Weak | 52 |
| 6 | Rain | 14 | Normal | Strong | 23 |
| 7 | Overcast | 15 | Normal | Strong | 43 |
| 8 | Sunny | 28 | High | Weak | 35 |
| 9 | Sunny | 10 | Normal | Weak | 38 |
| 10 | Rain | 24 | Normal | Weak | 46 |
| 11 | Sunny | 22 | Normal | Strong | 48 |
| 12 | Overcast | 26 | High | Strong | 52 |
| 13 | Overcast | 36 | Normal | Weak | 44 |
| 14 | Rain | 30 | High | Strong | 30 |
Effect of Tree Depth:
- With max_depth=2: The tree makes only a few cuts, resulting in a simpler, "step-like" prediction that may not capture finer variations in the data
- With max_depth=3: More splits lead to a more complex tree that can better adapt to variations in the data
- Trade-off:
- Lower depth: Higher bias (simpler model, fewer splits)
- Higher depth: Increases variance (more responsive to fluctuations in the data, risk of overfitting)
Overfitting in Regression Trees
Overfitting is a significant issue with regression trees:
Interactive Examples
MSE Calculation Example
Consider a house price prediction model with the following data:
| House Price ($1000s) y | Square Feet x |
|---|---|
| 245 | 1400 |
| 312 | 1600 |
| 279 | 1700 |
| 308 | 1875 |
| 199 | 1100 |
| 219 | 1550 |
| 405 | 2350 |
| 324 | 2450 |
| 319 | 1425 |
| 255 | 1700 |
Imagine a model made the following predictions:
| Actual (y) | Square Feet (x) | Predicted (ŷ) | Error | Error² |
|---|---|---|---|---|
| 245 | 1400 | 252 | -7 | 49 |
| 312 | 1600 | 273.9 | 38.1 | 1451.61 |
| 279 | 1700 | 284.9 | -5.9 | 34.81 |
| 308 | 1875 | 304.1 | 3.9 | 15.21 |
| 199 | 1100 | 219 | -20 | 400 |
| 219 | 1550 | 268.4 | -49.4 | 2440.36 |
| 405 | 2350 | 356.3 | 48.7 | 2371.69 |
| 324 | 2450 | 367.3 | -43.3 | 1874.89 |
| 319 | 1425 | 254.7 | 64.3 | 4134.49 |
| 255 | 1700 | 284.9 | -29.9 | 894.01 |
Calculate MSE:
KNN Regression Visualization
Consider a simple 1D regression problem:
Numerical Solutions
MSE, RMSE, and MAE Calculation
Given the following actual and predicted values:
| Actual (y) | Predicted (ŷ) | Error (y - ŷ) | Error² | |Error| |
|---|---|---|---|---|
| 10 | 12 | -2 | 4 | 2 |
| 15 | 14 | 1 | 1 | 1 |
| 20 | 18 | 2 | 4 | 2 |
| 25 | 27 | -2 | 4 | 2 |
| 30 | 28 | 2 | 4 | 2 |
Calculate:
KNN Regression Calculation
Given the following data points (x, y):
(1, 2), (2, 4), (3, 5), (4, 4), (5, 6), (6, 8), (7, 7), (8, 9)
Query point: x = 4.5
Calculate predictions for different K values:
Try It Yourself
Given the following actual and predicted values:
| Actual | Predicted |
|---|---|
| 5 | 7 |
| 10 | 8 |
| 15 | 16 |
| 20 | 19 |
Tasks:
- Calculate MSE
- Calculate RMSE
- Which metric is easier to interpret and why?
Solution:
- Errors: (5-7)=-2, (10-8)=2, (15-16)=-1, (20-19)=1
- Squared errors: 4, 4, 1, 1
- MSE: (4 + 4 + 1 + 1)/4 = 10/4 = 2.5
- RMSE: √2.5 ≈ 1.58
- Interpretability: RMSE is easier to interpret because it's in the same units as the target variable (2.5 vs 1.58, where 1.58 is more meaningful)
Given two models with the following errors on a test set:
Model A: Errors = [-3, -2, -1, 0, 1, 2, 3]
Model B: Errors = [-5, -1, -1, 0, 1, 1, 5]
Tasks:
- Calculate MAE for both models
- Calculate MSE for both models
- Which model performs better according to MAE?
- Which model performs better according to MSE?
- Which metric do you think is more appropriate here and why?
Solution:
- MAE:
- Model A: (3+2+1+0+1+2+3)/7 = 12/7 ≈ 1.71
- Model B: (5+1+1+0+1+1+5)/7 = 14/7 = 2.0
- MSE:
- Model A: (9+4+1+0+1+4+9)/7 = 28/7 = 4.0
- Model B: (25+1+1+0+1+1+25)/7 = 54/7 ≈ 7.71
- MAE winner: Model A (1.71 < 2.0)
- MSE winner: Model A (4.0 < 7.71)
- Appropriate metric: Both metrics agree that Model A is better. However, MSE penalizes Model B more heavily for its large errors (-5 and 5), which might be desirable if large errors are particularly bad. MAE is more robust to outliers.
Given the following training data (x, y):
(1, 3), (2, 5), (3, 7), (4, 9), (5, 11)
Query point: x = 3.5
Tasks:
- What is the prediction when K=1?
- What is the prediction when K=2?
- What is the prediction when K=3?
- As K increases, what happens to the prediction?
Solution:
- K=1: Nearest neighbor is (3, 7) or (4, 9). Assuming Euclidean distance, both are equally close (distance=0.5). Typically, we'd pick the first one: Prediction = 7
- K=2: Nearest neighbors: (3, 7) and (4, 9). Prediction = (7 + 9)/2 = 8
- K=3: Nearest neighbors: (2, 5), (3, 7), (4, 9). Prediction = (5 + 7 + 9)/3 ≈ 7
- As K increases: The prediction becomes more smoothed and approaches the average of all y values (7). With K=5, prediction = (3+5+7+9+11)/5 = 7.
Consider a simple dataset for predicting house prices based on square footage:
| Square Feet | Price ($1000s) |
|---|---|
| 1000 | 200 |
| 1200 | 220 |
| 1500 | 250 |
| 1800 | 300 |
| 2000 | 320 |
Task: If we're building a regression tree with max_depth=1 (one split), where would be the optimal split point to minimize MSE? Calculate the MSE for splits at 1300, 1400, 1600, and 1700 square feet.
Solution:
For each potential split, we calculate the MSE of the predictions:
Split at 1300:
- Left (≤1300): 1000(200), 1200(220) → mean = 210
- Right (>1300): 1500(250), 1800(300), 2000(320) → mean = 290
- MSE = [(200-210)² + (220-210)² + (250-290)² + (300-290)² + (320-290)²]/5
- = [100 + 100 + 1600 + 100 + 900]/5 = 2800/5 = 560
Split at 1400:
- Left (≤1400): 1000(200), 1200(220) → mean = 210
- Right (>1400): 1500(250), 1800(300), 2000(320) → mean = 290
- MSE = 560 (same as 1300)
Split at 1600:
- Left (≤1600): 1000(200), 1200(220), 1500(250) → mean = 223.33
- Right (>1600): 1800(300), 2000(320) → mean = 310
- MSE = [(200-223.33)² + (220-223.33)² + (250-223.33)² + (300-310)² + (320-310)²]/5
- = [537.78 + 11.11 + 711.11 + 100 + 100]/5 ≈ 1460/5 = 292
Split at 1700:
- Left (≤1700): 1000(200), 1200(220), 1500(250), 1800(300) → mean = 242.5
- Right (>1700): 2000(320) → mean = 320
- MSE = [(200-242.5)² + (220-242.5)² + (250-242.5)² + (300-242.5)² + (320-320)²]/5
- = [1806.25 + 506.25 + 56.25 + 3306.25 + 0]/5 = 5775/5 = 1155
Optimal split: At 1600 square feet with MSE = 292 (lowest MSE)
You are building a model to predict house prices, and your dataset contains some outliers (very expensive houses that are unusual for their size).
Tasks:
- Which evaluation metric would you choose: MSE, RMSE, or MAE?
- Why is this metric more appropriate?
- If you want to heavily penalize large errors (e.g., underestimating the price of an expensive house by a lot), which metric would you choose?
Solution:
- Recommended metric: MAE (Mean Absolute Error)
- Reason: MAE is more robust to outliers. Since the dataset contains outliers (very expensive houses), MSE and RMSE would be heavily influenced by these extreme values, giving a distorted view of typical model performance. MAE treats all errors equally, regardless of their magnitude.
- For penalizing large errors: MSE or RMSE. Both heavily penalize large errors due to the squaring operation. RMSE is often preferred because it's in the same units as the target variable, making it more interpretable.
Interactive Quiz
Test your understanding of KNN Regressor, Regression Trees, and Evaluation Metrics:
Question 1: What is the main difference between classification and regression?
Question 2: Which metric is most sensitive to outliers?
Question 3: In KNN regression, what happens to the prediction as K increases?
Question 4: In a regression tree, how is the value of a leaf node determined?
Question 5: What is the primary issue with regression trees without regularization?
Key Takeaways
Classification vs Regression:
- Output type: Classification predicts discrete labels, regression predicts continuous values
- Examples: Classification (spam detection, image classification), Regression (house price prediction, temperature forecasting)
- ML pipeline: Similar pipeline for both: data → preprocessing → train-test split → model training → prediction
- Key differences: Different loss functions, different evaluation metrics
Evaluation Metrics:
- MSE (Mean Squared Error): Average squared difference, penalizes large errors heavily, units are squared
- RMSE (Root Mean Squared Error): Square root of MSE, same units as target, penalizes large errors heavily
- MAE (Mean Absolute Error): Average absolute difference, robust to outliers, same units as target
KNN Regressor:
- Non-parametric: Makes no assumptions about the underlying data distribution
- Instance-based: Uses the entire training dataset for predictions (lazy learning)
- Prediction method: Averages (or weighted averages) of k-nearest neighbors' target values
- Distance metric: Typically Euclidean, but can use others (Manhattan, etc.)
- Strengths: Simple, works well for non-linear relationships with local patterns
- Weaknesses: Computationally expensive, sensitive to choice of k and distance metric
Regression Trees:
- Non-parametric: Makes no assumptions about the functional form
- Rule-based: Creates a series of if-then rules based on feature thresholds
- Leaf value: Average of training data in that leaf (unlike classification trees which use majority voting)
- Splitting criterion: Minimizes MSE (or variance) of the resulting subsets
- Strengths: Highly interpretable, can capture non-linear relationships, handles both numerical and categorical features
- Weaknesses: Prone to overfitting, can be unstable (small data changes can lead to different trees)
General Insights:
- Metric selection: Choose based on your priorities: MSE/RMSE for penalizing large errors, MAE for robustness to outliers
- Model selection: KNN for local patterns, Regression Trees for interpretable non-linear relationships
- Overfitting: Always a concern with flexible models like regression trees; use regularization or pruning
- Feature importance: Regression trees naturally provide feature importance scores
Common Pitfalls
⚠️ Evaluation Metrics:
- Using classification metrics: Never use accuracy, precision, recall, or F1-score for regression problems
- Ignoring units: MSE has squared units, which can be misleading. RMSE is often more interpretable
- Over-reliance on a single metric: Different metrics tell different stories. Use multiple metrics for a complete picture
- Comparing metrics across scales: Metrics like MSE/RMSE/MAE are scale-dependent. Standardize or use relative metrics when comparing across different datasets
⚠️ KNN Regressor:
- Choosing k: Too small k leads to noisy, overfit predictions; too large k leads to oversmoothed, high-bias predictions
- Distance metric: Euclidean distance assumes spherical neighborhoods, which may not be appropriate for all data distributions
- Feature scaling: Features must be scaled (standardized/normalized) when using Euclidean distance, otherwise features with larger scales will dominate
- Computational cost: KNN can be slow for large datasets, especially in high dimensions
- Curse of dimensionality: KNN performance degrades in high-dimensional spaces as all points become equally distant
⚠️ Regression Trees:
- Overfitting: Regression trees can easily overfit the training data, creating trees that are too complex
- No pruning: Without regularization (e.g., min_samples_leaf, max_depth), trees will grow until each leaf is pure or contains min_samples_split
- Unstable: Small changes in the data can lead to very different tree structures
- Biased towards dominant classes: In regions with few training samples, predictions may be unreliable
- Extrapolation: Regression trees perform poorly on data outside the range of the training data
- Feature importance bias: Trees tend to favor features with more possible split points (e.g., continuous over categorical)
⚠️ General:
- Data leakage: Ensure that preprocessing (scaling for KNN) is done correctly within cross-validation folds
- Ignoring assumptions: While tree-based methods make few assumptions, KNN assumes that nearby points have similar target values
- Target variable distribution: Both KNN and regression trees assume that the target variable is roughly continuous in the input space
Resources
📚 KNN Regressor:
- Scikit-learn KNN Regressor Documentation
- KNN for Regression - Detailed explanation
- KNN for Machine Learning - Comprehensive guide
📚 Regression Trees:
- Scikit-learn Decision Trees for Regression
- Step-by-Step Regression Tree Example - Practical walkthrough
- Decision Trees for Regression - Detailed tutorial
📚 Evaluation Metrics:
- Scikit-learn Regression Metrics
- Common Error Metrics for Regression
- Regression Metrics for Machine Learning
📖 Books:
- An Introduction to Statistical Learning by James et al. - Excellent coverage of regression methods
- Machine Learning with PyTorch and Scikit-Learn by Raschka et al.
- Hands-On Machine Learning with Scikit-Learn, Keras, and TensorFlow by Geron
💻 Practical Implementation:
- Google Colab - Free environment to experiment with regression models
- Kaggle: Regression Course - Hands-on tutorial
- Scikit-learn GitHub - Source code and examples